#include "LedControl.h"
#include <SerialLCD.h>
#include <Ultrasonic.h>

SerialLCD LCD;

Ultrasonic ultrasonic(8, 9);
LedControl lc=LedControl(12,11,10,1);

// Example 45.1 - tronixstuff.wordpress.com - CC by-sa-nc
// Connect Ping))) signal pin to Arduino digital 8
int signal = 8;
int signalIn = 9;

int distance;
int distanceant;
unsigned long pulseduration=0;

void setup()
{
  Serial.begin(9600);
  
  LCD.init();
  
  delay(2000);

  LCD.clear();


  lc.shutdown(0,false);
  /* Set the brightness to a medium values */
  lc.setIntensity(0, 5);
  /* and clear the display */
  lc.clearDisplay(0);
  
  
  //pinMode(signal, OUTPUT);
  //pinMode(signalIn, INPUT);

}

void measureDistance()
{
  // set output to LOW
  digitalWrite(signal, LOW);

  delayMicroseconds(5);

  // now send the 5uS pulse out to activate Ping)))
  digitalWrite(signal, HIGH);
  delayMicroseconds(5);
  digitalWrite(signal, LOW);

  // finally, measure the length of the incoming pulse
  pulseduration = pulseIn(signalIn, HIGH);
}
void loop()
{
  // get the raw measurement data from Ping)))
  //measureDistance();

  // divide the pulse length by half
  //pulseduration = pulseduration / 2; 

  // now convert to centimetres. We're metric here people...
  //distance = int(pulseduration / 29);

  distance = ultrasonic.Ranging();

  // Display on serial monitor
  Serial.print("Distancia - ");
  Serial.print(distance);
  Serial.println(" cm");
  
  if (distance > 500) 
   distance = 0; 

  if (distanceant !=  distance)
  {  
   lc.clearDisplay(0);

    if  ((((distance / 1000) % 10) > 0) || (((distance / 10000) % 10) > 0))  
      lc.setDigit(0, 3, (distance / 1000) % 10, false);
   
    if ((((distance / 100) % 10) > 0) || (((distance / 1000) % 10) > 0)) 
      lc.setDigit(0, 2, (distance / 100) % 10, false);
  
    if ((((distance / 10) % 10) > 0) || (((distance / 100) % 10) > 0))
      lc.setDigit(0, 1, (distance / 10) % 10, false);
   
    lc.setDigit(0, 0, distance % 10, false);
  }
  
  distanceant = distance;
  
  delay(100);
  
  
}

